import Konva from 'konva'
import { useEffect, useRef, useState } from 'react'
import { Circle, Group, Layer, Rect, Stage, Transformer } from 'react-konva'

export default function View() {
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [autoSelect, setAutoSelect] = useState(false)
  const rectRef = useRef<Konva.Rect>(null)
  const circleRef = useRef<Konva.Circle>(null)
  const transformerRef = useRef<any>(null)
  const maskGroupRef = useRef(null)
  const layerRef = useRef(null)

  useEffect(() => {
    if (!transformerRef.current) return
    let node = null
    if (selectedId === 'rect') {
      node = rectRef.current
    } else if (selectedId === 'circle') {
      node = circleRef.current
    }

    // 先将所有图形移动到主图层
    rectRef.current.moveTo(layerRef.current)
    circleRef.current.moveTo(layerRef.current)

    if (node) {
      transformerRef.current.nodes([node])
      if (!autoSelect) {
        // 将选中的图形移到遮罩组最上层
        maskGroupRef.current.moveToTop()
        node.moveTo(maskGroupRef.current)
      }
    } else {
      transformerRef.current.nodes([])
    }

    layerRef.current.batchDraw()
  }, [selectedId, autoSelect])

  const shapes = [
    { id: 'rect', name: '正方形' },
    { id: 'circle', name: '圆形' }
  ]

  const handleSelectChange = e => {
    setSelectedId(e.target.value || null)
  }

  const handleAutoSelectChange = e => {
    rectRef.current.moveTo(layerRef.current)
    circleRef.current.moveTo(layerRef.current)
    setAutoSelect(e.target.checked)
  }

  return (
    <div className='view-wrapper'>
      <div style={{ marginBottom: '10px' }}>
        <label style={{ marginRight: '20px' }}>
          <input type='checkbox' checked={autoSelect} onChange={handleAutoSelectChange} />
          自动选择
        </label>
        <select value={selectedId || ''} onChange={handleSelectChange} style={{ padding: '4px' }}>
          <option value=''>请选择图形</option>
          {shapes.map(shape => (
            <option key={shape.id} value={shape.id}>
              {shape.name}
            </option>
          ))}
        </select>
      </div>

      <Stage
        width={800}
        height={600}
        onClick={e => {
          if (e.target === e.target.getStage()) {
            setSelectedId(null)
          }
        }}
      >
        <Layer ref={layerRef}>
          <Rect
            id='rect'
            ref={rectRef}
            x={100}
            y={100}
            width={100}
            height={100}
            fill='red'
            onClick={() => setSelectedId('rect')}
          />
          <Circle
            id='circle'
            ref={circleRef}
            x={300}
            y={100}
            radius={50}
            fill='blue'
            onClick={() => setSelectedId('circle')}
          />
          <Transformer ref={transformerRef} />
          {!autoSelect && (
            <Group
              ref={maskGroupRef}
              draggable
              onDragEnd={e => {
                const node = e.target as Konva.Group
                const { x, y } = node.position()
                node.getChildren().forEach((child: any) => {
                  if (child.id() === 'maskRect') return

                  child.position({
                    x: x + child.position().x,
                    y: y + child.position().y
                  })
                })
                node.position({ x: 0, y: 0 })
              }}
            >
              <Rect id='maskRect' width={800} height={600} fill='rgba(0, 0, 0, 0.2)' />
            </Group>
          )}
        </Layer>
      </Stage>
    </div>
  )
}
